﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using ST.Common.Util.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace ST.Common.Util.Mvc
{
	public class BaseSearchModel
	{
		/// <summary>
		/// 当前页码（从1开始）
		/// </summary>
		public int? pnum { get; set; }

		/// <summary>
		/// 每页数量
		/// </summary>
		public int? psize { get; set; }

		/// <summary>
		/// 排序字段
		/// </summary>
		public string sortby { get; set; }

		/// <summary>
		/// 排序顺序
		/// </summary>
		public SortOrder orderby { get; set; }

		private string _sortorder;
		/// <summary>
		/// 排列字段和顺序（格式：字段名_顺序）
		/// </summary>
		public string sortorder
		{
			get
			{
				return _sortorder;
			}
			set
			{
				if (string.IsNullOrEmpty(value))
				{
					_sortorder = "ID_desc";
				}
				else
				{
					_sortorder = value;
				}
				if (_sortorder.EndsWith("_desc", StringComparison.OrdinalIgnoreCase))
				{
					sortby = _sortorder.Substring(0, _sortorder.Length - 5);
					orderby = SortOrder.Descending;
				}
				else if (_sortorder.EndsWith("_asc", StringComparison.OrdinalIgnoreCase))
				{
					sortby = _sortorder.Substring(0, _sortorder.Length - 4);
					orderby = SortOrder.Ascending;
				}
				else
				{
					sortby = _sortorder;
					orderby = SortOrder.Ascending;
				}
			}
		}

		/// <summary>
		/// 单位IDs
		/// </summary>
		public int[] orgids { get; set; }

		/// <summary>
		/// 单位ID
		/// </summary>
		public int? orgid { get; set; }

		public string orgname { get; set; }

		public BaseSearchModel()
		{
		}

		public virtual void Validate()
		{
			if (!pnum.HasValue || pnum.Value < 1)
			{
				throw new ArgumentException("页码不能小于1");
			}
			if (!psize.HasValue || psize.Value < 1)
			{
				throw new ArgumentException("每页显示条数不能小于1");
			}
		}

		public virtual void Validate(UserSession sessionCurrent, string actionCode)
		{
			Validate();
			if (sessionCurrent == null)
			{
				throw new AuthException("用户未登录或登录已过期");
			}
			if (sessionCurrent.Roles == null || sessionCurrent.Roles.Length == 0)
			{
				throw new AuthException("用户未授权");
			}
		}
	}
}
